package com.general.app.wjgl.action;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.general.app.wjgl.dao.entity.QuestionOption;
import com.general.app.wjgl.dao.entity.SurveyRebackModel;
import com.general.app.wjgl.dao.entity.SurveySendModel;
import com.general.app.wjgl.service.ISurveyRebackService;
import com.general.app.wjgl.service.ISurveySendService;
import com.general.app.xtgl.dao.entity.AssessUserModel;
import com.general.app.xtgl.service.IAssessUserService;
import com.general.common.action.BaseAction;
import com.general.common.mail.impl.JavaxMailServer;
import com.general.common.model.QueryModel;
import com.general.common.security.entity.User;
import com.general.utils.base.Constant;
import com.general.utils.base.StringUtil;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.util.ValueStack;

/**
 * 问卷发放管理
 * @author Administrator
 *
 */
public class SurveyRebackAction extends BaseAction implements ModelDriven<SurveyRebackModel>{

	private static final long serialVersionUID = -5571279048868407604L;
	
	private SurveyRebackModel model = new SurveyRebackModel();
	private ISurveyRebackService surveyRebackService;
	private IAssessUserService assessUserService;
	private ISurveySendService surveySendService;
	private JavaxMailServer mailServer;
	
	/**
	 * 问卷发放管理列表
	 * @return
	 */
	public String surveyRebackList(){
		if (QUERY.equals(model.getDoType())) {
			QueryModel queryModel = model.getQueryModel();
			try {
				// 单位列表
				if(Constant.TAB_COMPANY.equals(getRequest().getParameter("tab"))){

					queryModel.setItems(surveyRebackService.getPagedList(model));
					
					// 个人列表
				}else if(Constant.TAB_SINGEL.equals(getRequest().getParameter("tab"))){
					
					queryModel.setItems(surveyRebackService.getPagedUserList(model));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			getValueStack().set(DATA, queryModel);
			return DATA;
		}
		return "surveyRebackList";
	}	
	
	/**
	 * 问卷提醒
	 * @return
	 */
	public String answerMind(){
		
		String ids = getRequest().getParameter("ids");
		String tab = getRequest().getParameter("tab");
		try {
			// 发送邮件（需要优化）
			mailServer.sendMailList(surveySendService.getSendMindEmailList(tab, ids));

			String message = "问卷提醒成功！";
			getValueStack().set(DATA, message);

		} catch (Exception e) {
			e.printStackTrace();
			String message = "问卷提醒失败！";
			getValueStack().set(DATA, message);
		}
		return DATA;
	}
	
	/**
	 * 【不同评估者得分】统计情况
	 * @return
	 */
	public String assessRebackList(){
		if (QUERY.equals(model.getDoType())) {
			QueryModel queryModel = model.getQueryModel();
			// 三个拼接字段
			String ids = getRequest().getParameter("ids");
			try {
				model.setSend_id(ids);
				
				// 【不同评估者得分】统计情况
				queryModel.setItems(surveyRebackService.getAssessRebackList(model));
			} catch (Exception e) {
				e.printStackTrace();
			}
			getValueStack().set(DATA, queryModel);
			return DATA;
		}
		return "surveyFactorAverageList";
	}
	
	
	/**
	 * 【问卷因子平均分】统计情况
	 * @return
	 */
	public String surveyFactorAverageList(){
		if (QUERY.equals(model.getDoType())) {
			QueryModel queryModel = model.getQueryModel();
			// 三个拼接字段
			String ids = getRequest().getParameter("ids");
			try {
				model.setSend_id(ids);
				// 【问卷因子平均分】统计情况
				queryModel.setItems(surveyRebackService.getSurveyFactorAverageList(model));
			} catch (Exception e) {
				e.printStackTrace();
			}
			getValueStack().set(DATA, queryModel);
			return DATA;
		}
		return "surveyFactorAverageList";
	}
	
	/**
	 * 查看问卷信息
	 * @return
	 */
	public String showSurveyReback(){

		ValueStack vs = getValueStack();
		// 三个拼接字段
		String ids = getRequest().getParameter("ids");
		String tab = getRequest().getParameter("tab");
		try {
			// 统计字段
			SurveyRebackModel rebackModel = surveyRebackService.getRackModel(ids, tab);
			rebackModel.setTab(tab);
			vs.set("model", rebackModel);
			BeanUtils.copyProperties(model, rebackModel);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "showSurveyReback";
	}
	
	/**
	 * 查看个人统计信息
	 * @return
	 */
	public String showUserSurStat(){

		ValueStack vs = getValueStack();
		String tab = Constant.TAB_SINGEL;
		String ids = getRequest().getParameter("ids");
		
		try {
			
			// 个人问卷回收信息
			SurveyRebackModel rebackModel = surveyRebackService.getRackModel(ids, tab);			
			model.setSend_id(ids);
			Map<String,Object> map = getUserSurStatAll(ids);
			vs.set("assessmodel", map.get("assessmodel"));
			vs.set("rebackmodel", rebackModel);
			vs.set("surveysendmodelist", map.get("surveysendmodelist"));
			vs.set("allQuestionList", map.get("allQuestionList"));
			vs.set("openQuestionList", map.get("openQuestionList"));
			vs.set("speQuestionList", map.get("speQuestionList"));
			vs.set("ids", ids);		
			
			BeanUtils.copyProperties(model, rebackModel);
			
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return "showUserSurStat";
	}
	
	/**
	 * 取得所有个人统计信息
	 * @param ids
	 * @return
	 */
	private Map<String,Object> getUserSurStatAll(String ids){
		
		String tab = Constant.TAB_SINGEL;
		Map<String,Object> map = new HashMap<String,Object>();
		try {

			String[] pks = ids.split("_");
			
			// 个人问卷回收信息
			SurveyRebackModel rebackModel = surveyRebackService.getRackModel(ids, tab);
			
			// 个人简单信息取得
			AssessUserModel assuserModel = assessUserService.getModel(pks[2]);
			
			// 取得回答问卷人的回答情况[列表]
			List<SurveySendModel> surveySendModellst = surveySendService.getAssessSendList(ids);
			
			model.setSend_id(ids);
			
			// 【360评分全貌图】列表
			List<SurveyRebackModel> allQuestiongGet = surveyRebackService.getAllQuestionList(model);

			List<SurveyRebackModel> allQuestionList = new ArrayList<SurveyRebackModel>();
			String questionId = "";
			List<QuestionOption> allRelationList = new ArrayList<QuestionOption>();
			
			SurveyRebackModel open = new SurveyRebackModel();
			for(int i =0;i<allQuestiongGet.size();i++){
				
				SurveyRebackModel openQ = allQuestiongGet.get(i);	
				
				// 判断是否新题
				if(StringUtil.isEmpty(questionId) || !questionId.equals(openQ.getQuestion_id())){					
					// 
					if(open.getQuestion_id()!=null && !StringUtil.isEmpty(open.getQuestion_id())){
						open.setOpenRelationList(allRelationList);
						allQuestionList.add(open);
					}
					
					//新建
					open = new SurveyRebackModel();
					open.setFactor_id(openQ.getFactor_id());
					open.setFactor_name(openQ.getFactor_name());
					open.setQuestion_id(openQ.getQuestion_id());
					open.setQuestion_name(openQ.getQuestion_name());
					open.setKeyword(openQ.getKeyword());
					
					questionId = openQ.getQuestion_id();
					allRelationList = new ArrayList<QuestionOption>();
					allRelationList = getFormatQuestionOption();
				}
				// 设置
				for(QuestionOption s : allRelationList){
					if(openQ.getRelation().equals(s.getId())){
						s.setScore(openQ.getRelation_assess());
					}
				}
				
				// 设置关系列表
				if(i == allQuestiongGet.size()-1){
					open.setOpenRelationList(allRelationList);
					allQuestionList.add(open);					
				}
			}
			
			model.setSend_id(ids);
			
			// 【开放性问题】列表 STYLE_ID：3
			List<SurveyRebackModel> openQuestionGet = surveyRebackService.getOpenQuestionList(model);
			
			List<SurveyRebackModel> openQuestionList = new ArrayList<SurveyRebackModel>();
			questionId = "";
			List<QuestionOption> qstionRelationList = new ArrayList<QuestionOption>();
			
			open = new SurveyRebackModel();
			for(int i =0;i<openQuestionGet.size();i++){
				
				SurveyRebackModel openQ = openQuestionGet.get(i);	
				QuestionOption qstionRelation = new QuestionOption();
				// 判断是否新题
				if(StringUtil.isEmpty(questionId) || !questionId.equals(openQ.getQuestion_id())){					
					// 
					if(open.getQuestion_id()!=null && !StringUtil.isEmpty(open.getQuestion_id())){
						open.setOpenRelationList(qstionRelationList);
						openQuestionList.add(open);	
					}
					
					//新建
					open = new SurveyRebackModel();
					open.setQuestion_id(openQ.getQuestion_id());
					open.setQuestion_name(openQ.getQuestion_name());
					open.setKeyword(openQ.getKeyword());
					
					questionId = openQ.getQuestion_id();
					qstionRelationList = new ArrayList<QuestionOption>();
				}
				// 设置
				qstionRelation.setName(openQ.getRelation_name());
				qstionRelation.setContent(openQ.getText());
				qstionRelationList.add(qstionRelation);
				
				// 设置关系列表
				if(i == openQuestionGet.size()-1){
					open.setOpenRelationList(qstionRelationList);
					openQuestionList.add(open);					
				}
			}
			
			model.setSend_id(ids);
			
			// 【个别特殊问题】列表 spemark：2
			List<SurveyRebackModel> speQuestionList = surveyRebackService.getSpeQuestionList(model);
			map.put("assessmodel", assuserModel);
			map.put("rebackmodel", rebackModel);
			map.put("surveysendmodelist", surveySendModellst);
			map.put("allQuestionList", allQuestionList);
			map.put("openQuestionList", openQuestionList);
			map.put("speQuestionList", speQuestionList);
			map.put("ids", ids);			
			
			return map;
			
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return map;
	}
	/**
	 * 导出个人统计信息
	 * @return
	 * @throws IOException 
	 */
	public String dcUserSurStat() throws IOException {

		User user = getCurrentUser();
		getResponse();
		String ids = getRequest().getParameter("ids");
		
		// 取得数据集
		Map<String, Object> map = getUserSurStatAll(ids);

		// 【问卷因子平均分】统计情况
		model.setSend_id(ids);
		map.put("surveyFactorAverageList",surveyRebackService.getSurveyFactorAverageList(model) );

		model.setSend_id(ids);
		// 【不同评估者得分】统计情况
		map.put("assessRebackList",surveyRebackService.getAssessRebackList(model));
		
		
		OutputStream ouputStream = null;
		try {
			// 返回xls
			HSSFWorkbook wb = surveyRebackService.dcUserSurStat(map, user,
					getResponse());
			getResponse().reset();
			getResponse().setContentType("application/vnd.ms-excel;charset=UTF-8");
			// 个人问卷回收信息
			SurveyRebackModel rebackModel = (SurveyRebackModel) map
					.get("rebackmodel");
			
			String fileName = "360问卷个人统计-" + rebackModel.getAssess_user_nm();
			getResponse().setHeader("Content-disposition",
					"attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO-8859-1") + ".xls");
			//getResponse().setContentType("application/ms-excel;charset=UTF-8");
			//getResponse().setHeader("Content-disposition", "attachment; " +
			//		"filename=" + new String("360問卷調查-個人統計".getBytes("GBK"), "ISO-8859-1") + ".xls"); 
			ouputStream = getResponse().getOutputStream();
			
			wb.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ouputStream != null)
				ouputStream.close();
		}
        
		return null;
	}
	
	/**
	 * 格式化360全面列表
	 * @return
	 */
	private List<QuestionOption> getFormatQuestionOption(){
		List<QuestionOption> allRelationList = new ArrayList<QuestionOption>();

		QuestionOption ss = new QuestionOption();
		//关系ID
		ss.setId("0");
		//关系名
		ss.setName("上级");
		//分数
		ss.setScore("");
		allRelationList.add(ss);
		
		ss = new QuestionOption();
		//关系ID
		ss.setId("1");
		//关系名
		ss.setName("平级");
		//分数
		ss.setScore("");
		allRelationList.add(ss);
		
		ss = new QuestionOption();
		//关系ID
		ss.setId("2");
		//关系名
		ss.setName("下属");
		//分数
		ss.setScore("");
		allRelationList.add(ss);
		
		ss = new QuestionOption();
		//关系ID
		ss.setId("3");
		//关系名
		ss.setName("自评");
		//分数
		ss.setScore("");
		allRelationList.add(ss);
		
		return allRelationList;
	}
	
	public JavaxMailServer getMailServer() {
		return mailServer;
	}

	public void setMailServer(JavaxMailServer mailServer) {
		this.mailServer = mailServer;
	}

	public SurveyRebackModel getModel() {
		return model;
	}

	public void setModel(SurveyRebackModel model) {
		this.model = model;
	}

	public ISurveyRebackService getSurveyRebackService() {
		return surveyRebackService;
	}

	public void setSurveyRebackService(ISurveyRebackService surveyRebackService) {
		this.surveyRebackService = surveyRebackService;
	}

	public IAssessUserService getAssessUserService() {
		return assessUserService;
	}

	public void setAssessUserService(IAssessUserService assessUserService) {
		this.assessUserService = assessUserService;
	}

	public ISurveySendService getSurveySendService() {
		return surveySendService;
	}

	public void setSurveySendService(ISurveySendService surveySendService) {
		this.surveySendService = surveySendService;
	}
}
